#!/usr/bin/env python
# coding:gbk
from __future__ import unicode_literals
from cStringIO import StringIO

from pdfminer.pdfinterp import PDFResourceManager,  PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage

def getPdfText(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = file(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()
    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
        interpreter.process_page(page)
    fp.close()
    device.close()
    str = retstr.getvalue()
    retstr.close()
    return str



def main():
    import sys

    if len(sys.argv) < 2:
        sys.stderr.write(' usage: pdf2text.py <pdffiles...>\n')
        exit(1)

    for fname in sys.argv[1:]:
        print getPdfText(fname)


def test():
    filename = 'f:\\1.pdf'
    text = getPdfText(filename)
    print type(text)
    text2 = unicode(text, 'utf-8')
    print type(text2)
    print text2


if __name__ == '__main__':
    test()


